import { defineStore, StoreDefinition } from "pinia";
import { RouteLocationNormalized } from "vue-router";
import { MenuOption, NIcon } from "naive-ui";
import { nameHome, nameTest } from "../router/app";
import { nameSqlHome } from "../router/sql";
import { h } from "vue";
import { renderIconByName } from "../Icon";

export function newDefaultTab(): ITab {
  return { closeable: true, name: "default", label: "默认" };
}

export function newTabFromRoute(route: RouteLocationNormalized): ITab {
  const tab = newDefaultTab();
  tab.name = <string>route.name;
  tab.label = <string>route.name;

  return tab;
}

interface ITab {
  name: string;
  label: string; // 显示的标签
  closeable: boolean;
}

function findITabByName(name: string) {
  return function (value: ITab) {
    return value.name === name;
  };
}

interface store {
  current: string; // 当前选中的 Tab
  tabs: ITab[];
  collapsed: boolean;
  menu: MenuOption[];
}

export const useLayoutStore = defineStore({
  // 它用于 devtools 并允许恢复状态
  id: "layout",
  state: (): store => ({
    current: "home",
    tabs: [
      {
        name: "home",
        label: "首页",
        closeable: false,
      },
    ],
    collapsed: true,
    menu: [],
  }),
  actions: {
    addTabByRoute(route: RouteLocationNormalized) {
      const value = this.tabs.find(findITabByName(<string>route.name));

      if (!value) {
        this.tabs.push(newTabFromRoute(route));
      }
    },
    removeTabByName(name: string) {
      const value = this.tabs.findIndex(findITabByName(name));
      if (value !== -1) {
        this.tabs.splice(value, 1);
      }
      // 删除当前 tab 时换前一个页面
      if (name === this.current) {
        this.current = this.tabs[Math.min(value, this.tabs.length - 1)].name;
      }
    },
  },
});

export function initLayoutStore() {
  useLayoutStore().menu = [
    {
      label: "首页",
      key: nameHome,
      icon: renderIconByName("home"),
    },
    {
      label: "SQL管理",
      key: nameSqlHome,
      icon: renderIconByName("database"),
    },
    {
      label: "测试页面",
      key: nameTest,
    },
  ];
}
